﻿package idv.cjcat.emitter.behaviors {
	use namespace engine;
	
	import flash.xml.*;
	
	import idv.cjcat.emitter.*;
	
	public class CompositeTrigger extends BehaviorTrigger {
		
		public var behaviorTriggers:Array;
		
		private var mode:uint;
		
		public function CompositeTrigger(behaviorTriggers:Array = null, mode:uint = 0) {
			this.behaviorTriggers = behaviorTriggers;
			this.mode = mode;
		}
		
		override public function test(pd:ParticleData):Boolean {
			if (behaviorTriggers == null) return false;
			
			var bt:BehaviorTrigger;
			switch (mode) {
				case CompositeTriggerMode.AND:
					for each (bt in behaviorTriggers) {
						if (!bt.test(pd)) return false;
					}
					return true;
					break;
				case CompositeTriggerMode.OR:
					for each (bt in behaviorTriggers) {
						if (bt.test(pd)) return true;
					}
					return false;
					break;
			}
			return false;
		}
		
		
		//XML
		//------------------------------------------------------------------------------------------------
		
		override public function toXML():XML {
			var xml:XML = super.toXML();
			xml.@type = BehaviorTriggerType.COMPOSITE;
			xml.@mode = mode.toString();
			
			var behaviorTriggersXML:XML = <behaviorTriggers/>;
			for each (var bt:BehaviorTrigger in behaviorTriggers) {
				var btID:XML = <id/>;
				btID.@value = bt._id;
				behaviorTriggersXML.appendChild(btID);
			}
			xml.appendChild(behaviorTriggersXML);
			
			return xml;
		}
		override public function parseXML(xml:XML):void {
			super.parseXML(xml);
			mode = parseInt(xml.@mode);
			
			var temp:Array = new Array();
			for each (var node:XML in xml.behaviorTriggers.id) {
				temp.push(EmitterGlobal.getBehaviorTriggerByID(node.@value));
			}
			
			behaviorTriggers = temp;
		}
		
		//------------------------------------------------------------------------------------------------
		//end of XML
	}
}